<template>
  <view class="profile-container">
    <view class="profile-header">
      <view class="avatar-container" @click="changeAvatar">
        <image :src="userInfo.avatar || defaultAvatar" class="avatar"></image>
        <view class="avatar-edit-icon">
          <text class="iconfont icon-edit"></text>
        </view>
      </view>
      <view class="user-info">
        <text class="username">姓名：{{ userInfo.name || '未设置姓名' }}</text>
        <text class="account">账号：{{ userInfo.account || '未知' }}</text>
        <text class="warehouse">所属仓库：{{ userInfo.warehouse || '暂未绑定仓库' }}</text>
      </view>
    </view>

    <view class="profile-menu">
      <view class="menu-item" @click="navigateTo('/pages/profile/changePassword')">
        <text class="iconfont icon-lock"></text>
        <text class="menu-text">修改密码</text>
        <text class="iconfont icon-right"></text>
      </view>
      <view class="menu-item" @click="logout">
        <text class="iconfont icon-logout"></text>
        <text class="menu-text">退出登录</text>
        <text class="iconfont icon-right"></text>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'

export default {
  data() {
    return {
      userInfo: {
        name: '',
        account: '',
        warehouse: '',
        avatar: ''
      },
      defaultAvatar: '/static/default-avatar.png'
    }
  },
  onShow() {
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      // 从本地存储获取账号名
      const sorterAccount = uni.getStorageSync('sorterAccount')

      //打印sorterAccount
      console.log("sorterAccount:"+sorterAccount)

      try {
        const res = await request({
          url: '/sorter/profile',
          method: 'GET',
          data: {
            // 将账号名作为参数传递
            sorterAccount: sorterAccount
          }
        })

        if (res.code === 200) {
          // 合并用户信息，确保所有字段都有默认值
          this.userInfo = {
            name: res.data.sorterName || '未设置姓名',
            account: res.data.sorterAccount || sorterAccount,
            warehouse: res.data.warehouseName || '暂未绑定仓库',
            avatar: res.data.img_src || this.defaultAvatar
          }
        } else {
          // 如果获取用户信息失败，清除本地存储并跳转到登录页
          uni.removeStorageSync('sorterAccount')
          uni.removeStorageSync('token')
          uni.reLaunch({
            url: '/pages/second/sorterSecond'
          })
        }
      } catch (err) {
        console.error('获取用户信息失败:', err)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        
        // 清除本地存储并跳转到登录页
        uni.removeStorageSync('sorterAccount')
        uni.removeStorageSync('token')
        uni.reLaunch({
          url: '/pages/second/sorterSecond'
        })
      }
    },
    changeAvatar() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: async (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths
          
          // 上传头像
          try {
            const uploadRes = await this.uploadAvatar(tempFilePaths[0])
            
            if (uploadRes.code === 200) {
              this.userInfo.avatar = uploadRes.data.avatarUrl
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              })
            }
          } catch (err) {
            console.error('头像上传失败:', err)
            uni.showToast({
              title: '头像上传失败',
              icon: 'none'
            })
          }
        }
      })
    },
    async uploadAvatar(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: '/sorter/uploadAvatar',
          filePath: filePath,
          name: 'avatar',
          success: (uploadFileRes) => {
            const data = JSON.parse(uploadFileRes.data)
            resolve(data)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    },
    navigateTo(url) {
      uni.navigateTo({ url })
    },
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储
            uni.removeStorageSync('userInfo')
            uni.removeStorageSync('token')
            uni.removeStorageSync('sorterAccount')

            // 直接跳转到登录页
            uni.reLaunch({
              url: '/pages/index/index'
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.profile-container {
  background-color: #f4f4f4;
  min-height: 100vh;
}

.profile-header {
  background-color: #007aff;
  color: white;
  padding: 40px 20px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin-bottom: 15px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3px solid white;
}

.avatar-edit-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.5);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-edit-icon .iconfont {
  color: white;
  font-size: 16px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.username {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}

.account {
  font-size: 14px;
  color: rgba(255,255,255,0.8);
  margin-bottom: 8px;
}

.warehouse {
  font-size: 14px;
  color: rgba(255,255,255,0.8);
}

.profile-menu {
  background-color: white;
  margin: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-item .iconfont {
  font-size: 20px;
  margin-right: 15px;
  color: #666;
}

.menu-item .menu-text {
  flex-grow: 1;
  font-size: 16px;
}

.menu-item .icon-right {
  color: #999;
}
</style> 